# Copyright 2010 Mikko Rantanen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import cmdbase
import os
import logging
import bus.channel as channel

class Cmd(cmdbase.CmdBase):
    """Shows the meta properties of an object"""

    name = "props"
    aliases = "p"

    @staticmethod
    def get_params(args):
        p = args.pop()
        vault, relpath = Cmd.fspath(p)
        return vault, { 'path' : relpath }

    @staticmethod
    def execute(vault, args):
        logging.debug("Processing 'props' command")
        fsentry = vault.get_child(args['path'])
        ov = fsentry.iteminfo['ObjVer']
        conn = vault.get_conn()
        obj = conn.resource('objects', ov['Type'], ov['ID'], ov['Version'])

        props = obj.get('displayproperties')
        propdefs = conn.get('structure/propertyDefs')

        pdmap = {}
        for pd in propdefs:
            pdmap[pd['ID']] = pd

        pvals = []
        for p in props:
            if not p['TypedValue']: continue

            pvals.append({
                'property': pdmap[p['PropertyDef']]['Name'],
                'value': p['TypedValue']['DisplayValue'] })

        return { 'properties' : pvals }

    @staticmethod
    def output(result):
        namelength = 0
        for p in result['properties']:
            plen = len(p['property'])
            if plen > namelength:
                namelength = plen

        for p in result['properties']:
            print "%-*s%s" % (namelength+3, p['property'] + ":", p['value'])
            

